"use client";

import React from "react";
import commonStyles from "./common.module.scss";
import { Checkbox, Form } from "antd";

type PropsType = {
  id: string;
  props: ComponentPropsType;
};

type ComponentPropsType = {
  title: string;
  list: Array<{
    label: string;
    value: string;
    checked: boolean;
  }>;
  prompt?: string[];
  isVertical: boolean;
  isRequired?: boolean;
  isRandom?: boolean;
  answer?: string[];
};

const QuestionCheckbox: React.FC<PropsType> = ({ id, props }) => {
  const { title, list = [], isVertical, isRequired, answer } = props;
  const formatValue = list.filter((i) => i.checked).map((i) => i.value);

  return (
    <Form.Item
      label={title}
      name={id}
      initialValue={answer || formatValue}
      rules={[{ required: !!isRequired, message: "不能为空" }]}
      className={`${isVertical ? commonStyles.vertical : ""} ${
        commonStyles.h5
      }`}
    >
      <Content data={props} />
    </Form.Item>
  );
};

export default QuestionCheckbox;

function Content(props: any) {
  const { data, ...otherProps } = props;
  const {
    list = [],
    prompt = [],
    isRandom,
    answer,
  } = data as ComponentPropsType;
  const formatList = list.map((i) => ({
    label: (
      <span
        style={{
          color:
            answer && answer.includes(i.value)
              ? prompt.includes(i.value)
                ? "#52c41a"
                : "#ff4d4f"
              : "black",
        }}
      >
        {i.label}
      </span>
    ),
    value: i.value,
  }));
  const formatValue = list.filter((i) => i.checked).map((i) => i.value);
  const formatPromptList = prompt.map(
    (i) => list.find((j) => j.value === i)?.label
  );

  return (
    <div className={commonStyles.content}>
      <Checkbox.Group
        options={formatList}
        disabled={!!answer}
        defaultValue={answer || formatValue}
        {...otherProps}
      />
      {answer && !isRandom && (
        <div
          style={{
            color: "#52c41a",
          }}
        >
          提示答案：{formatPromptList.join("、")}
        </div>
      )}
    </div>
  );
}
